package week02

import "math"

// 875. 爱吃香蕉的珂珂
// https://leetcode-cn.com/problems/koko-eating-bananas/

func minEatingSpeed(piles []int, h int) int {
	var minSpeed, maxSpeed = 1, 0
	for _, pile := range piles {
		maxSpeed += pile
	}
	for minSpeed < maxSpeed {
		var speed = (maxSpeed - minSpeed) / 2 + minSpeed
		if isValid(piles, h, speed) {
			maxSpeed = speed
		} else {
			minSpeed = speed + 1
		}
	}
	return minSpeed
}

func isValid(piles []int, h int, speed int) bool {
	var needH = 0
	for _, pile := range piles {
		needH += int(math.Ceil((float64(pile) / float64(speed))))
	}
	return needH <= h
}
